package com.mycar2w.cloud.service.serviceimpl;

import com.mycar2w.cloud.entity.ApplieOrder;
import com.mycar2w.cloud.entity.Car;
import com.mycar2w.cloud.entity.CarBasicParameter;
import com.mycar2w.cloud.entity.CarChassisBrakeParameter;
import com.mycar2w.cloud.entity.CarEngineParameter;
import com.mycar2w.cloud.entity.CarInnerConfigutation;
import com.mycar2w.cloud.entity.CarOutConfiguration;
import com.mycar2w.cloud.entity.CarSecurityConfiguration;
import com.mycar2w.cloud.entity.CarSystemTestBrakeEnginecompartment;
import com.mycar2w.cloud.entity.CarSystemTestChassis;
import com.mycar2w.cloud.entity.CarSystemTestIndicatorLight;
import com.mycar2w.cloud.entity.CarTestAccelerate;
import com.mycar2w.cloud.entity.CarTestDecelerationBraking;
import com.mycar2w.cloud.entity.CarTestStart;
import com.mycar2w.cloud.entity.CarTestStartup;
import com.mycar2w.cloud.entity.CarTestUniformDriving;
import com.mycar2w.cloud.entity.TTransaction;
import com.mycar2w.cloud.entity.TUser;
import com.mycar2w.cloud.service.pojo.TransactionPost;
import com.mycar2w.cloud.service.repository.ApplieOrderRepository;
import com.mycar2w.cloud.service.repository.CarBasicParameterR;
import com.mycar2w.cloud.service.repository.CarChassisBrakeParameterR;
import com.mycar2w.cloud.service.repository.CarEngineParameterR;
import com.mycar2w.cloud.service.repository.CarInnerConfigutationR;
import com.mycar2w.cloud.service.repository.CarOutConfigurationR;
import com.mycar2w.cloud.service.repository.CarRepository;
import com.mycar2w.cloud.service.repository.CarSecurityConfigurationR;
import com.mycar2w.cloud.service.repository.CarSystemTestBrakeEnginecompartmentR;
import com.mycar2w.cloud.service.repository.CarSystemTestChassisR;
import com.mycar2w.cloud.service.repository.CarSystemTestIndicatorLightR;
import com.mycar2w.cloud.service.repository.CarTestAccelerateR;
import com.mycar2w.cloud.service.repository.CarTestDecelerationBrakingR;
import com.mycar2w.cloud.service.repository.CarTestStartR;
import com.mycar2w.cloud.service.repository.CarTestStartupR;
import com.mycar2w.cloud.service.repository.CarTestUniformDrivingR;
import com.mycar2w.cloud.service.repository.TTransactionRepository;
import com.mycar2w.cloud.service.repository.TUserRepository;
import com.mycar2w.cloud.service.utils.ConvertString;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * created time 2017/4/7
 *
 * @author ljc
 * @version V1.0
 */
@Service
public class MasterService {

    @Autowired
    private ApplieOrderRepository applieOrderRepository;
    @Autowired
    private TUserRepository tUserRepository;
    @Autowired
    private TTransactionRepository tTransactionRepository;
    @Autowired
    private CarRepository carRepository;
    @Autowired
    private CarBasicParameterR carBasicParameterR;
    @Autowired
    private CarChassisBrakeParameterR carChassisBrakeParameter;
    @Autowired
    private CarEngineParameterR carEngineParameterR;
    @Autowired
    private CarInnerConfigutationR carInnerConfigutationR;
    @Autowired
    private CarSecurityConfigurationR carSecurityConfigurationR;
    @Autowired
    private CarSystemTestBrakeEnginecompartmentR carSystemTestBrakeEnginecompartmentR;
    @Autowired
    private CarSystemTestChassisR carSystemTestChassisR;
    @Autowired
    private CarSystemTestIndicatorLightR carSystemTestIndicatorLightR;
    @Autowired
    private CarTestAccelerateR carTestAccelerateR;
    @Autowired
    private CarTestDecelerationBrakingR carTestDecelerationBrakingR;
    @Autowired
    private CarTestStartR carTestStartR;
    @Autowired
    private CarTestStartupR carTestStartupR;
    @Autowired
    private CarTestUniformDrivingR carTestUniformDrivingR;
    @Autowired
    private CarOutConfigurationR carOutConfigurationR;

    public List<ApplieOrder> findAppliOrders(Integer category, Integer pageIndex) {
        Page<ApplieOrder> applieOrders=applieOrderRepository.findByIsOver(category,pageIndex);
        return applieOrders.getContent();
    }

    public ApplieOrder findApplieOrder(Long orderId) {
        ApplieOrder applieorder=applieOrderRepository.findById(orderId);
        return applieorder;
    }
    @Transactional
    public void updateOrder(ApplieOrder applieOrder) {
        applieOrderRepository.saveAndFlush(applieOrder);
    }

    public void createTransaction(TransactionPost transactionPost) {
        TUser tBuyUser=tUserRepository.findByPhone(transactionPost.getBuyUserPhone());
        TUser tSaleUser= tUserRepository.findByPhone(transactionPost.getSaleUserPhone());
        TTransaction tTransaction=new TTransaction();
        tTransaction.setId(new Date().getTime());
        tTransaction.setCarId(carRepository.findByAppliedOrderId(applieOrderRepository.findById(transactionPost.getApplieOrderId())).getId());
        tTransaction.setBuyUserId(tBuyUser.getId());
        tTransaction.setSaleUserId(tSaleUser.getId());
        tTransaction.setCreateTime(new Timestamp(System.currentTimeMillis()));
        tTransactionRepository.save(tTransaction);
    }
    @Transactional
    public void upFile(MultipartFile file, ApplieOrder applieOrder, Long userId, Long carId,String imgs) {
        InputStream is;
        try {

            Object obj=null;
            String fileNameOrginal=file.getOriginalFilename();
            if (StringUtils.isNotBlank(fileNameOrginal)){
                if(!fileNameOrginal.substring(fileNameOrginal.length()-3,fileNameOrginal.length()).equals("jpg")) {
                    String classFileName = ConvertString.convert(fileNameOrginal).replace(".xls","");
                    is = file.getInputStream();
                    Workbook wb = new HSSFWorkbook(is);
                    //获得第一个表单
                    Sheet sheet = wb.getSheetAt(0);
                    //获得第一个表单的行迭代器
                    Iterator<Row> rows = sheet.rowIterator();
                    Iterator<Row> rows2 = sheet.rowIterator();
                    //第1行
                    Row row = rows.next();
                    //第2行
                    rows2.next();
                    Row rowTwo = rows2.next();
                    Iterator<Cell> cells = row.cellIterator();
                    Iterator<Cell> cellsNext = rowTwo.cellIterator();
                    Method method;
                    Class<?> classLoad = null;
                    String val = null;
                    String val2 = null;
                    classLoad = Class.forName("com.mycar2w.cloud.entity." + classFileName);
                    obj = classLoad.newInstance();
                    while (cells.hasNext()) {
                        Cell cell = cells.next();
                        Cell valval = null;
                        if (cellsNext.hasNext()) {
                            valval = cellsNext.next();
                        }
                        val = swithcDup(cell);
                        val2 = swithcDup(valval);


                        String originalMethod = ConvertString.convert(val);
                        if (!originalMethod.equals("UserId") &&!originalMethod.equals("CarId") && !originalMethod.equals("Id") && !originalMethod.equals("AppliedOrderId") &&
                                !originalMethod.equals("LastModifirdTime") && !originalMethod.equals("CeateTime")) {
                            method = classLoad.getMethod("set" + originalMethod, String.class);
                            method.invoke(obj, val2);
                        }

                    }
                    if (classFileName.equals("Car")) {
                        method = classLoad.getMethod("setImages", String.class);
                        method.invoke(obj, imgs);
                        method = classLoad.getMethod("setId", Long.class);
                        method.invoke(obj, carId);
                        method = classLoad.getMethod("setAppliedOrderId", ApplieOrder.class);
                        method.invoke(obj, applieOrder);
                        method = classLoad.getMethod("setUserId", Long.class);
                        method.invoke(obj, userId);
                        method = classLoad.getMethod("setCarMasterDescription", String.class);
                        method.invoke(obj,applieOrder.getCarDescrip());
                        method = classLoad.getMethod("setLastModifirdTime", Timestamp.class);
                        method.invoke(obj, new Timestamp(System.currentTimeMillis()));
                        method = classLoad.getMethod("setCeateTime", Timestamp.class);
                        method.invoke(obj, new Timestamp(System.currentTimeMillis()));

                    } else {
                        method = classLoad.getMethod("setId", Long.class);
                        method.invoke(obj, carId);
                        method = classLoad.getMethod("setCarId", Long.class);
                        method.invoke(obj, carId);
                    }
                    switch (classFileName) {
                        case "Car":
                            carRepository.save((Car) obj);
                            break;
                        case "CarBasicParameter":
                            carBasicParameterR.save((CarBasicParameter) obj);
                            break;
                        case "CarChassisBrakeParameter":
                            carChassisBrakeParameter.save((CarChassisBrakeParameter) obj);
                            break;
                        case "CarEngineParameter":
                            carEngineParameterR.save((CarEngineParameter) obj);
                            break;
                        case "CarInnerConfigutation":
                            carInnerConfigutationR.save((CarInnerConfigutation) obj);
                            break;
                        case "CarOutConfiguration":
                            carOutConfigurationR.save((CarOutConfiguration) obj);
                            break;
                        case "CarSecurityConfiguration":
                            carSecurityConfigurationR.save((CarSecurityConfiguration) obj);
                            break;
                        case "CarSystemTestBrakeEnginecompartment":
                            carSystemTestBrakeEnginecompartmentR.save((CarSystemTestBrakeEnginecompartment) obj);
                            break;
                        case "CarSystemTestChassis":
                            carSystemTestChassisR.save((CarSystemTestChassis) obj);
                            break;
                        case "CarSystemTestIndicatorLight":
                            carSystemTestIndicatorLightR.save((CarSystemTestIndicatorLight) obj);
                            break;
                        case "CarTestAccelerate":
                            carTestAccelerateR.save((CarTestAccelerate) obj);
                            break;
                        case "CarTestDecelerationBraking":
                            carTestDecelerationBrakingR.save((CarTestDecelerationBraking) obj);
                            break;
                        case "CarTestStart":
                            carTestStartR.save((CarTestStart) obj);
                            break;
                        case "CarTestStartup":
                            carTestStartupR.save((CarTestStartup) obj);
                            break;
                        case "CarTestUniformDriving":
                            carTestUniformDrivingR.save((CarTestUniformDriving) obj);
                            break;

                    }
                    is.close();
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    public String swithcDup(Cell cell){
        String val=null;
        switch (cell.getCellType()) {
            case HSSFCell.CELL_TYPE_NUMERIC:
                double number = cell.getNumericCellValue();
                if (number == (int) number) {
                    //整数
                    val = String.valueOf((int) number);
                } else {
                    //包含小数的double
                    val = String.valueOf(cell.getNumericCellValue());
                }
                break;
            case HSSFCell.CELL_TYPE_STRING:
                val = cell.getStringCellValue();
                break;
            case HSSFCell.CELL_TYPE_BOOLEAN:
                val = String.valueOf(cell.getBooleanCellValue());
                break;
        }
        return val;
    }
}
